﻿using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Reflection;
using System.Transactions;
using WebCoreAPI.Models;

namespace WebCoreAPI.Filter
{
    public class SelfActionFilter : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            ControllerActionDescriptor? descriptor = context.ActionDescriptor as ControllerActionDescriptor;
            if (descriptor != null)
            {
                var cusattr = descriptor.MethodInfo.GetCustomAttribute<SelfTransactionAttribute>(); //可以拿到值
                //var attr = descriptor.MethodInfo.IsDefined(typeof(SelfTransactionAttribute));
                if (cusattr != null)
                {
                    //当对Action加上了[SelfTransaction]标签后，就开启事务
                    using TransactionScope tx = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
                    ActionExecutedContext result = await next();
                    if (result.Exception == null)
                    {
                        tx.Complete();
                        return;
                    }
                }
            }
            //Action执行前
            await next();
            //Action执行后
        }
    }
}
